package gui.VPOfOperations;

import javax.swing.JTabbedPane;
import javax.swing.JPanel;

import net.miginfocom.swing.MigLayout;

import javax.swing.JOptionPane;
import javax.swing.JToggleButton;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.RowSorter;

import java.awt.ComponentOrientation;
import java.awt.FlowLayout;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.border.BevelBorder;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

import clients.RPCClient;

import com.sun.xml.internal.ws.api.Component;

import entities.PolishReportEntity;
import eu.hansolo.steelseries.tools.Model;

import java.awt.BorderLayout;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

import javax.swing.JLabel;

import java.awt.Font;

import javax.swing.Box;

import utilities.PrintActionListener;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.ImageIcon;
import javax.swing.border.TitledBorder;

import java.awt.SystemColor;
import java.awt.Color;
/**
 * 
 * @author adam
 *Polish report panel used by the VPO .
 */
public class VPOfOperationsTabbedPolishReport extends JPanel{

	private VPOfOperationsTabbedPolishReport myPolishReport;
	private VPOfOperationsReports myVPOfReports;
	private VPOfOperationsTabbedPane myTabbedPane;
	private JTable table;
	private float startDiopter;
	private float endDiopter;
	private String startDate;
	private String endDate;
	private RPCClient myRPC;
	private DefaultTableModel model;
	public Boolean isEmpty = false;
	private String family;
/**
 * Constructor	
 * @param myTabbedPane
 * @param myVPOfReports
 * @param startDiopter
 * @param endDiopter
 * @param startDate
 * @param endDate
 * @param family
 */
	public VPOfOperationsTabbedPolishReport(VPOfOperationsTabbedPane myTabbedPane, VPOfOperationsReports myVPOfReports,float startDiopter , float endDiopter,String startDate , String endDate,String family)
	{
		setBackground(new Color(173, 216, 230));
		this.myTabbedPane=myTabbedPane;
		this.myVPOfReports=myVPOfReports;
		this.myPolishReport=this;
		this.startDiopter=startDiopter;
		this.endDiopter=endDiopter;
		this.startDate=startDate;
		this.endDate=endDate;
		this.family=family;
		
		try
		{
			myRPC = new RPCClient();
			initialize();
			model = (DefaultTableModel) table.getModel();
			initializeTableVariables();

			
		}
		catch(Exception e)
		{
			//e.printStackTrace();
		}
		
		
	}
	/**
	 * initializes the panel with selected settings
	 */	
	public void initialize()
	{
		setLayout(new MigLayout("", "[grow]", "[][grow][][grow][][grow][][grow]"));
		
		//Formating Date format from "dd/mm/yyyy" to "yyyy/MM/dd"
				final String OLD_FORMAT = "dd/MM/yyyy";
				final String NEW_FORMAT = "yyyy/MM/dd";
				String oldDateStringBegin = startDate;
				String oldDateStringEnd = endDate;
				String newDateString=null;
				String newDateStringg=null;
				try{
					SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
					SimpleDateFormat sdff= new SimpleDateFormat(OLD_FORMAT);
					java.util.Date d = sdf.parse(oldDateStringBegin);
					java.util.Date dd = sdff.parse(oldDateStringEnd);
					sdf.applyPattern(NEW_FORMAT);
					sdff.applyPattern(NEW_FORMAT);
					newDateString = sdf.format(d);
					newDateStringg = sdff.format(dd);
					newDateString.toString();
					newDateStringg.toString();
				}catch(Exception e)
				{
					//e.printStackTrace();
				}
		
		java.awt.Component verticalStrut = Box.createVerticalStrut(5);
		add(verticalStrut, "cell 0 0,aligny center");

		JPanel panel = new JPanel(){@Override
			public void paintComponent(Graphics g) {
	        Graphics2D g2d = (Graphics2D) g;
	        Color color1 = getBackground();
	        Color color2 = color1.darker();
	        int w = getWidth();
	        int h = getHeight(); 
	        GradientPaint gp = new GradientPaint(
	                0, 0, color1,
	                0, h, color2);

	        g2d.setPaint(gp);
	        g2d.fillRect(0, 0, w, h);
	        }};
		panel.setBackground(new Color(173, 216, 230));
		panel.setBorder(new TitledBorder(null, "דוחות ליטוש מתאריך "+newDateString+" ועד תאריך "+newDateStringg, TitledBorder.CENTER, TitledBorder.TOP, null, null));
		add(panel, "cell 0 5,grow");
		panel.setLayout(new BorderLayout(0, 0));
		
		JScrollPane scrollPane = new JScrollPane();
		panel.add(scrollPane);
		
		table = new JTable();
		table.setFont(new Font("Tahoma", Font.PLAIN, 15));
		table.setModel(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
				"\u05DE\u05DB\u05D5\u05E0\u05D4", "\u05EA\u05D0\u05E8\u05D9\u05DA \u05E1\u05D9\u05D5\u05DD", "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D4\u05EA\u05D7\u05DC\u05D4", "\u05DE\u05E1\u05E4\u05E8 \u05E6\u05E0\u05E6\u05E0\u05EA", "\u05DB\u05DE\u05D5\u05EA", "\u05D3\u05D9\u05D5\u05E4\u05D8\u05E8", "\u05E1\u05D5\u05D2", "\u05E4\u05E7\"\u05E2"
			}
		) {
			boolean[] columnEditables = new boolean[] {
				false, false, false, false, false, false, false, false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		table.setSize(panel.getSize());
		
		scrollPane.setViewportView(table);
		scrollPane.setSize(panel.getSize());
		
		JButton btnNewButton = new JButton("יצא לאקסל");
		btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
		btnNewButton.setIcon(new ImageIcon(VPOfOperationsTabbedPolishReport.class.getResource("/graphics/excel.png")));
		btnNewButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
//JTable table = utilities.Services.parsePivotTableToJTrable(myTable);
				
				ArrayList<Object> result = utilities.Services.exportToExcel(table);
				if (result.get(0).equals(true))
				{
					// confirm
					JOptionPane.showMessageDialog(panel,
							result.get(1).toString() + " :הדוח נשמר " ,"אישור",JOptionPane.INFORMATION_MESSAGE);
				}
				else
				{
					// error
					JOptionPane.showMessageDialog(panel,
						    "לא ניתן לשמור את הדוח.","שגיאה",JOptionPane.ERROR_MESSAGE);
				}
				//new Thread(new PrintActionListener(mainPanel)).start();
			
			}
		});
		
		JButton btnNewButton_1 = new JButton("סגירת דוח");
		btnNewButton_1.setFont(new Font("Tahoma", Font.PLAIN, 13));
		btnNewButton_1.setIcon(new ImageIcon(VPOfOperationsTabbedPolishReport.class.getResource("/graphics/back.png")));
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				myTabbedPane.remove(myTabbedPane.getSelectedIndex());
			}
		});
		add(btnNewButton_1, "flowx,cell 0 6,alignx center");
		add(btnNewButton, "cell 0 6,alignx center");
	}
/**
 * Initializes the Polish report , gets the relevant variables needed in the table	
 * @throws Exception
 */
	public void initializeTableVariables() throws Exception
	{
		ArrayList<Object>message = new ArrayList<>();
		ArrayList<Object>respond = new ArrayList<>();
		
		//Row Sorter 
		 RowSorter<DefaultTableModel> sorter = new TableRowSorter<DefaultTableModel>(model);
		 table.setRowSorter(sorter);
		 //Row sorter end
		
		message.add("initializeVPOfOperationsTabbedPolishReport");
		message.add(startDate);
		message.add(endDate);
		message.add(this.startDiopter);
		message.add(this.endDiopter);
		message.add(this.family);
		
		respond = myRPC.call(message);
	//	System.out.println(respond.get(1).toString());
		if(respond.get(1).toString().equalsIgnoreCase("unvalid"))
		{
			JOptionPane.showMessageDialog(myTabbedPane, "לא נמצאו דוחות פוליש בתאריכים שנבחרו במערכת");
		}
		else {
			Iterator itr = respond.iterator();
			itr.next();itr.next();
			while(itr.hasNext())
			{
				PolishReportEntity myEntity = new PolishReportEntity();
				myEntity = (PolishReportEntity)itr.next();
				model.addRow(new Object[]{myEntity.getTopline(),myEntity.getEndDate(),myEntity.getBeginDate(),myEntity.getJarID(),myEntity.getQuantity(),myEntity.getDiopter(),myEntity.getType(),myEntity.getOrderID()});
				
				
			}
			
		}
		if(model.getRowCount()==0)
			isEmpty=true;
		
	}
	
	
	
	@Override
	public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    Color color1 = getBackground();
    Color color2 = color1.darker();
    int w = getWidth();
    int h = getHeight(); 
    GradientPaint gp = new GradientPaint(
            0, 0, color1,
            0, h, color2);

    g2d.setPaint(gp);
    g2d.fillRect(0, 0, w, h);
    }
	
	
	
	
}
